package plat

import (
	"encoding/json"
	"errors"
	"fmt"
	"strconv"
	"time"

	"github.com/cihub/seelog"
	"publish/app/account/model"
)

var (
	// 最多获取90天
	baijia_profit    = "/builder/author/income/totalIncomeDetail?startDate=%d&endDate=%d&pageIndex=1&num=90&listType=0&is_export=0"
	baijia_statistic = "/builder/author/statistic/appStatistic"

	baijia_zhishu          = "/builderinner/api/content/app/userHisScore"
	baijia_zhishu_postdata = "app_id=%s&start_date=%s&end_date=%s"
	baijia_appinfo         = "/builder/app/appinfo"
)

func init() {
	RegisterPlat("BAIJIA", newplat_baijia())
}

type platbaijia struct {
}

func newplat_baijia() Plat {
	return &platbaijia{}
}


func (p *platbaijia) GetProfit(account *model.Account, start, end time.Time) ([]AccountProfit, error) {
	phttp := newbaijia(account.GetCookie())
	v := fmt.Sprintf(baijia_profit, start.Unix(), end.Unix())
	body, err := phttp.getReq(phttp.url(v), "X-Requested-With", "XMLHttpRequest")
	if err != nil {
		return nil, err
	}
	var data BaijiaProfitResp
	if err := json.Unmarshal(body, &data); err != nil {
		return nil, err
	}

	if data.Errno != 0 {
		return nil, errors.New("get profit return errorms = " + data.Errmsg)
	}

	rets := make([]AccountProfit, 0)
	for _, profit := range data.Data.List {
		val, _ := strconv.ParseInt(profit.DayTime, 10, 64)
		valDate := time.Unix(val, 0)
		rets = append(rets, AccountProfit{
			AccountId: account.Id,
			Profit:    profit.TotalIncome,
			Time:      time.Now().Format("2006-01-02 15:04:05"),
			Date:      valDate.Format("2006-01-02"),
		})
	}
	return rets, nil
}

func (p *platbaijia) GetIndex(account *model.Account, start, end time.Time) ([]AccountData, error) {
	// TODO  	postdata := fmt.Sprintf(baijia_zhishu_postdata, account.Appcode, start.Format("20060102"), end.Format("20060102"))
	postdata := fmt.Sprintf(baijia_zhishu_postdata, account.PlatParams, start.Format("20060102"), end.Format("20060102"))
	phttp := newbaijia(account.GetCookie())
	body, err := phttp.postReq(phttp.url(baijia_zhishu), "form", postdata)
	if err != nil {
		return nil, err
	}
	var data BaijiahaoZhishu
	if err := json.Unmarshal(body, &data); err != nil {
		return nil, err
	}

	if data.Errno != 0 {
		return nil, errors.New("get zhishu return errorms = " + data.Errmsg)
	}

	var result []Zhishu
	if err := json.Unmarshal(data.Data, &result); err != nil {
		return nil, err
	}

	rets := make([]AccountData, 0)
	for _, index := range result {
		rets = append(rets, AccountData{
			AccountId: account.Id,
			Index:     index.Score,
			Time:      time.Now().Format("2006-01-02 15:04:05"),
			Date:      index.ScoreDate,
			IndexJson: map[string]interface{}{
				"original": index.Original,
				"domain":   index.Domain,
				"interest": index.Interest,
				"active":   index.Active,
				"quality":  index.Quality,
			},
		})
	}

	return rets, nil
}

func (p *platbaijia) GetEveryStatistic(account *model.Account,start,end time.Time)([]EveryDayStatisttic, error){
	return nil,nil
}

func (p *platbaijia) GetStatistic(account *model.Account, start, end time.Time) ([]AccountStatisttic, error) {

	types := []string{"news", "gallery", "video"}
	ret := make([]AccountStatisttic, 0)
	for _, tp := range types {
		stats, err := p.get_statistic(account, tp, start, end)
		if err != nil {
			seelog.Errorf("shucron statistic run: GetStatistic error = %v, account.id = %d, type = %s", err, account.Id, tp)
			continue
		}
		ret = append(ret, stats...)
	}
	return ret, nil
}

func (p *platbaijia) get_statistic(account *model.Account, tp string, start, end time.Time) ([]AccountStatisttic, error) {

	data := map[string]interface{}{
		"is_yesterday": false,
		"type":         tp,
		"start_day":    start.Format("20060102"),
		"end_day":      end.Format("20060102"),
	}
	phttp := newbaijia(account.GetCookie())
	body, err := phttp.postReq(phttp.url(baijia_statistic), "form", data, "X-Requested-With", "XMLHttpRequest")
	if err != nil {
		return nil, err
	}

	var resp BaijiaStatisticResp
	if err := json.Unmarshal(body, &resp); err != nil {
		return nil, err
	}

	if resp.Errno != 0 {
		return nil, errors.New("get statistic return errormsg = " + resp.Errmsg)
	}

	datas := make([]AccountStatisttic, 0)
	now := time.Now().Format("2006-01-02 15:04:05")
	for _, stat := range resp.Data.List {
		if stat.ViewCount < 0 {
			stat.ViewCount = 0
		}
		if stat.RecommendCount < 0 {
			stat.RecommendCount = 0
		}
		datas = append(datas, AccountStatisttic{
			AccountId: account.Id,
			Num:       stat.ViewCount,
			Type:      "reads_" + tp,
			Time:      now,
			Date:      stat.EventDay,
		}, AccountStatisttic{
			AccountId: account.Id,
			Num:       stat.RecommendCount,
			Type:      "recommends_" + tp,
			Time:      now,
			Date:      stat.EventDay,
		})
	}
	return datas, nil
}

func (p *platbaijia) GetLevel(account *model.Account) (string, error) {
	phttp := newbaijia(account.GetCookie())
	body, err := phttp.getReq(phttp.url(baijia_appinfo), "Referer", phttp.url("/builder/rc/preload"), "X-Requested-With", "XMLHttpRequest")
	if err != nil {
		return "", err
	}
	var data BaijiaAppinfoResp
	if err := json.Unmarshal(body, &data); err != nil {
		return "", err
	}

	if data.Errno != 0 {
		return "", errors.New("get baijia level return errorms = " + data.Errmsg)
	}

	if data.Data.User.AppLevel > 0 {
		return LEVEL_MONEY, nil
	}
	return LEVEL_NEW, nil
}

func (p *platbaijia) GetArticles(account *model.Account, start time.Time, end time.Time) ([]Article, error) {
	articles := []Article{}
	page := 1
	for {
		api := fmt.Sprintf(`http://baijiahao.baidu.com/builder/article/lists?type=&collection=&pageSize=10&currentPage=%d`, page)
		phttp := newbaijia(account.GetCookie())
		bodybytes, err := phttp.getReq(api)
		if err != nil {
			return nil, err
		}

		datas := BaijiaArticleListResp{}
		if err := json.Unmarshal(bodybytes, &datas); err != nil {
			return nil, err
		}

		if len(datas.Data.List) == 0 {
			return articles, nil
		}

		for _, data := range datas.Data.List {
			statusMsg := ""
			status := 1
			if data.BadStatus == "similar_1" {
				statusMsg = "文章重复"
			}
			if data.BadStatus == "similar_2" {
				statusMsg = "与百家号文章高度相似"
			}
			if data.Status == "rejected" {
				status = 4
			}
			isRecommend := false
			if data.IsRecommend == 1 {
				isRecommend = true
			}
			t, _ := time.Parse("2006-01-02 15:04:05", data.Time)

			if t.Before(start) {
				return articles, nil
			}

			if t.Before(end) {
				articles = append(articles, Article{
					Title:       data.Title,
					Url:         data.Url,
					Time:        t,
					Status:      status,
					FailMsg:     statusMsg,
					IsRecommend: isRecommend,
				})
			}
		}

		page++
	}

	return articles, nil
}

/*
http://cep.baidu.com/api/js/finances/payments?begin=20180301&end=20180305&metrics=income&timeGranularity=day
*/
func (p *platbaijia) GetPayRecord(account *model.Account, start time.Time, end time.Time) ([]PayRecord, error) {
	startTime := start.Format("20060102")
	endTime := end.Format("20060102")
	api := fmt.Sprintf(`http://cep.baidu.com/api/js/finances/payments?begin=%s&end=%s&metrics=income&timeGranularity=day`, startTime, endTime)
	phttp := newbaijia(account.GetCookie())
	bodybytes, err := phttp.getReq(api)
	if err != nil {
		return nil, err
	}

	datas := BaijiaPays{}
	if err := json.Unmarshal(bodybytes, &datas); err != nil {
		return nil, err
	}
	records := []PayRecord{}
	for _, data := range datas.Results {
		status := ""
		if data.ActualPay > 0 && data.Status == "" {
			status = "计税中"
		} else if data.ActualPay > 0 {
			status = "未支付"
		}
		if data.Status == "PAYED" {
			status = "已支付"
		}
		record := PayRecord{
			Date:              data.Date,
			MonthlyIncome:     data.MonthlyIncome,
			ActualPay:         data.ActualPay,
			ActualPayAfterTax: data.ActualPayAfterTax,
			Tax:               data.Tax,
			HavePay:           data.HavePay,
			Status:            status,
		}
		records = append(records, record)
	}

	return records, nil
}
func (p *platbaijia) GetFinancialInformation(account *model.Account) (*FinancialInformation, error) {
	api := `http://cep.baidu.com/api/js/finances/information`

	phttp := newbaijia(account.GetCookie())
	bodybytes, err := phttp.getReq(api)
	if err != nil {
		return nil, err
	}

	datas := BaiduFinancialInformation{}
	if err := json.Unmarshal(bodybytes, &datas); err != nil {
		return nil, err
	}
	fi := &FinancialInformation{}
	fi.PeopleName = datas.RegisterName
	fi.BankAccountName = datas.RegisterName
	fi.BankName = datas.Bank
	fi.SubBank = datas.SubBank
	fi.Locaiton = datas.AccTown
	fi.BankAccountNumber = datas.BankNumber
	fi.Code = datas.RegisterNum

	return fi, nil

}
